<template>
  <div class="inventory-management">
    <!-- 顶部搜索和筛选 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索商品名称或编号"
          @input="handleSearch"
        >
        <i class="fas fa-search"></i>
      </div>
      <div class="filters">
        <select v-model="categoryFilter">
          <option value="">全部分类</option>
          <option v-for="category in categories" :key="category" :value="category">
            {{ category }}
          </option>
        </select>
        <select v-model="stockFilter">
          <option value="">库存状态</option>
          <option value="low">库存不足</option>
          <option value="normal">库存正常</option>
          <option value="high">库存充足</option>
        </select>
      </div>
      <button class="export-btn" @click="exportInventory">
        <i class="fas fa-download"></i>
        导出库存
      </button>
    </div>

    <!-- 库存列表 -->
    <div class="inventory-table">
      <table>
        <thead>
          <tr>
            <th>商品图片</th>
            <th>商品名称</th>
            <th>商品编号</th>
            <th>分类</th>
            <th>当前库存</th>
            <th>库存状态</th>
            <th>最近更新</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in filteredInventory" :key="item.product._id">
            <td>
              <img :src="item.product.images[0]" :alt="item.product.name" class="product-image">
            </td>
            <td>{{ item.product.name }}</td>
            <td>{{ item.product._id }}</td>
            <td>{{ item.product.category }}</td>
            <td>
              <span :class="getStockClass(item.quantity)">
                {{ item.quantity }}
              </span>
            </td>
            <td>
              <span class="status-tag" :class="getStockLevel(item.quantity)">
                {{ getStockLevelText(item.quantity) }}
              </span>
            </td>
            <td>{{ formatDate(item.updatedAt) }}</td>
            <td>
              <div class="action-buttons">
                <button class="update-btn" @click="handleUpdate(item)">
                  <i class="fas fa-edit"></i>
                </button>
                <button class="history-btn" @click="viewHistory(item)">
                  <i class="fas fa-history"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span>第 {{ currentPage }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>

    <!-- 更新库存弹窗 -->
    <div class="modal" v-if="showUpdateModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>更新库存</h3>
          <button class="close-btn" @click="showUpdateModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="confirmUpdate">
            <div class="form-group">
              <label>商品名称</label>
              <input type="text" :value="selectedItem?.product.name" disabled>
            </div>
            <div class="form-group">
              <label>当前库存</label>
              <input type="number" :value="selectedItem?.quantity" disabled>
            </div>
            <div class="form-group">
              <label>变更类型</label>
              <select v-model="updateForm.type" required>
                <option value="in">入库</option>
                <option value="out">出库</option>
                <option value="adjust">调整</option>
              </select>
            </div>
            <div class="form-group">
              <label>变更数量</label>
              <input 
                type="number" 
                v-model="updateForm.quantity" 
                min="1"
                required
              >
            </div>
            <div class="form-group">
              <label>备注</label>
              <textarea v-model="updateForm.remark" rows="3"></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showUpdateModal = false">取消</button>
              <button type="submit" class="submit-btn">确认更新</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 库存记录弹窗 -->
    <div class="modal" v-if="showHistoryModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>库存记录</h3>
          <button class="close-btn" @click="showHistoryModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="product-info" v-if="selectedItem">
            <img :src="selectedItem.product.images[0]" :alt="selectedItem.product.name">
            <div>
              <h4>{{ selectedItem.product.name }}</h4>
              <p>当前库存：{{ selectedItem.quantity }}</p>
            </div>
          </div>
          
          <div class="history-list">
            <div v-for="record in historyRecords" :key="record._id" class="history-item">
              <div class="history-type" :class="record.type">
                {{ getHistoryTypeText(record.type) }}
              </div>
              <div class="history-content">
                <div class="history-main">
                  <span class="quantity" :class="record.type">
                    {{ record.type === 'out' ? '-' : '+' }}{{ record.quantity }}
                  </span>
                  <span class="operator">{{ record.operator }}</span>
                </div>
                <div class="history-detail">
                  <span class="time">{{ formatDate(record.createdAt) }}</span>
                  <span class="remark">{{ record.remark }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { inventoryApi } from '@/api'

// 状态变量
const inventory = ref([])
const searchQuery = ref('')
const categoryFilter = ref('')
const stockFilter = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const showUpdateModal = ref(false)
const showHistoryModal = ref(false)
const selectedItem = ref(null)
const historyRecords = ref([])

// 更新表单
const updateForm = ref({
  type: 'in',
  quantity: 1,
  remark: ''
})

// 分类列表
const categories = [
  '手机数码',
  '电脑办公',
  '家用电器',
  '服装鞋包',
  '食品生鲜',
  '图书音像'
]

// 过滤库存列表
const filteredInventory = computed(() => {
  return inventory.value.filter(item => {
    const matchQuery = item.product.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                      item.product._id.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchCategory = !categoryFilter.value || item.product.category === categoryFilter.value
    const matchStock = !stockFilter.value || getStockLevel(item.quantity) === stockFilter.value
    return matchQuery && matchCategory && matchStock
  })
})

// 获取库存状态
const getStockLevel = (quantity: number) => {
  if (quantity <= 10) return 'low'
  if (quantity <= 50) return 'normal'
  return 'high'
}

// 获取库存状态文本
const getStockLevelText = (quantity: number) => {
  const levels = {
    low: '库存不足',
    normal: '库存正常',
    high: '库存充足'
  }
  return levels[getStockLevel(quantity)]
}

// 获取库存数量样式
const getStockClass = (quantity: number) => {
  return {
    'text-danger': quantity <= 10,
    'text-warning': quantity > 10 && quantity <= 50,
    'text-success': quantity > 50
  }
}

// 获取历史记录类型文本
const getHistoryTypeText = (type: string) => {
  const types = {
    in: '入库',
    out: '出库',
    adjust: '调整'
  }
  return types[type as keyof typeof types]
}

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchInventory()
}

// 更新库存
const handleUpdate = (item: any) => {
  selectedItem.value = item
  showUpdateModal.value = true
}

// 确认更新
const confirmUpdate = async () => {
  if (!selectedItem.value) return

  try {
    const newQuantity = updateForm.value.type === 'out'
      ? selectedItem.value.quantity - updateForm.value.quantity
      : updateForm.value.type === 'in'
        ? selectedItem.value.quantity + updateForm.value.quantity
        : updateForm.value.quantity

    await inventoryApi.update(selectedItem.value.product._id, newQuantity)
    
    const index = inventory.value.findIndex(item => item.product._id === selectedItem.value.product._id)
    if (index !== -1) {
      inventory.value[index].quantity = newQuantity
    }
    
    showUpdateModal.value = false
    updateForm.value = {
      type: 'in',
      quantity: 1,
      remark: ''
    }
  } catch (error) {
    console.error('Failed to update inventory:', error)
  }
}

// 查看历史记录
const viewHistory = async (item: any) => {
  selectedItem.value = item
  showHistoryModal.value = true
  
  try {
    const response = await inventoryApi.getHistory(item.product._id)
    historyRecords.value = response.data
  } catch (error) {
    console.error('Failed to fetch history:', error)
  }
}

// 导出库存
const exportInventory = () => {
  // 实现导出逻辑
}

// 获取库存列表
const fetchInventory = async () => {
  try {
    const response = await inventoryApi.getList({
      page: currentPage.value,
      category: categoryFilter.value,
      stockLevel: stockFilter.value
    })
    inventory.value = response.data
    totalPages.value = Math.ceil(response.total / response.pageSize)
  } catch (error) {
    console.error('Failed to fetch inventory:', error)
  }
}

// 初始化
fetchInventory()
</script>

<style scoped>
.inventory-management {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.filters {
  display: flex;
  gap: 16px;
}

.filters select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.export-btn {
  padding: 8px 16px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.inventory-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 500;
  color: #666;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.text-danger {
  color: #ff4d4f;
}

.text-warning {
  color: #faad14;
}

.text-success {
  color: #52c41a;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-tag.low {
  background: #fff1f0;
  color: #ff4d4f;
}

.status-tag.normal {
  background: #fff7e6;
  color: #faad14;
}

.status-tag.high {
  background: #f6ffed;
  color: #52c41a;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.update-btn {
  background: #e6f7ff;
  color: #1890ff;
}

.history-btn {
  background: #f9f0ff;
  color: #722ed1;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.product-info {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.product-info img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info h4 {
  margin: 0 0 8px 0;
}

.product-info p {
  margin: 0;
  color: #666;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  display: flex;
  gap: 16px;
}

.history-type {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  min-width: 48px;
  text-align: center;
}

.history-type.in {
  background: #f6ffed;
  color: #52c41a;
}

.history-type.out {
  background: #fff1f0;
  color: #ff4d4f;
}

.history-type.adjust {
  background: #e6f7ff;
  color: #1890ff;
}

.history-content {
  flex: 1;
}

.history-main {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.quantity {
  font-weight: bold;
}

.quantity.in {
  color: #52c41a;
}

.quantity.out {
  color: #ff4d4f;
}

.quantity.adjust {
  color: #1890ff;
}

.operator {
  color: #666;
}

.history-detail {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}
</style> 